package com.xuhai.book.util;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.xuhai.book.bean.Token;
import com.xuhai.book.bean.Userinfo;
import com.xuhai.book.mapper.TokenMapper;
import com.xuhai.book.mapper.UserinfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    /*
    * servlet四大作用域
    * request作用域：只在当前请求中有效
    * session作用域：只在一次会话中有效(浏览器打开则会话开始，浏览器关闭则会话结束)
    * page作用域：在JSP页面中有效
    * application作用域：项目存活阶段有效(Tomcat启动则开始，Tomcat关闭则销毁)
    * */

    @Autowired
    private TokenMapper tokenMapper;

    @Autowired
    private ServletContext context;

    @Autowired
    private UserinfoMapper userinfoMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "token,content-type");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        /*请求头中包含了有效的token则表示已登录，否则直接返回错误信息*/
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            response.getWriter().println(JSON.toJSON(new RTException("未携带token",401)));
            return false;
        }
        Token tokenBean = tokenMapper.selectByToken(token);
        if(tokenBean!=null && tokenBean.getExpires().getTime() > System.currentTimeMillis()){
            Userinfo userinfo= userinfoMapper.selectByPrimaryKey(tokenBean.getUserId());
            context.setAttribute(token,userinfo);
            return true;
        }else{
            response.getWriter().println(JSON.toJSON(new RTException("未携带token",401)));
            return false;
        }
    }
}
